package com.fantasybaby.dao;

import java.util.List;
import java.util.Map;
import java.util.Set;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;

import com.fantasybaby.conInterface.IBaseDao;
import com.fantasybaby.db.HibernateSessionFactory;
import com.fantasybaby.page.Pager;
import com.fantasybaby.page.SystemContext;

public class BaseDaoImpl<T> implements IBaseDao<T> {
	@Override
	public void add(T t) {
		Session session = HibernateSessionFactory.getSession();
		session.save(t);
	}

	@Override
	public void delete(T t) {
		Session session = HibernateSessionFactory.getSession();
		session.delete(t);
	}

	@Override
	public void update(T t) {
		Session session = HibernateSessionFactory.getSession();
		session.update(t);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<T> findAll(Class<T> cl) {
		Session session = HibernateSessionFactory.getSession();
		return (List<T>) session.createQuery("from "+cl.getSimpleName()).list();
	}

	@SuppressWarnings("unchecked")
	@Override
	public Pager<T> findPage(Class<T> cl, Map<String, Object> map) {
		Session session = HibernateSessionFactory.getSession();
		Criteria criteria = session.createCriteria(cl);
		if (map != null) {
			Set<String> keySet = map.keySet();
			for (String key : keySet) {
				criteria.add(Restrictions.like(key, map.get(key)));
			}	
		}
		Integer pageSize = SystemContext.getPageSize();
		Integer pageNo = SystemContext.getPageIndex();
		int rowCount =  ((Long)criteria.setProjection(  
                Projections.rowCount()).uniqueResult()).intValue();
		criteria.setFirstResult((pageNo-1)*pageSize);   
		criteria.setMaxResults(pageSize);
		criteria.setProjection(null);
		List<T> list = criteria.list();
		Pager<T> pager = new Pager<T>();
		pager.setDatas(list);
		pager.setTotalRecord(rowCount, pageSize);
		pager.setPageIndex(pageNo);
		return pager;
	}

	@Override
	public int findPageCount(Class<T> cl, Map<String, Object> map) {
		Session session = HibernateSessionFactory.getSession();
		Criteria criteria = session.createCriteria(cl);
		int rowCount = (Integer) criteria.setProjection(  
                Projections.rowCount()).uniqueResult();
		return rowCount;
	}

	@SuppressWarnings("unchecked")
	@Override
	public T load(Class<T> cl,int id) {
		Session session = HibernateSessionFactory.getSession();
		return 	(T) session.get(cl, id);
	}
}
